package com.avic.rong.activity.no;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.alipay.sdk.app.PayTask;
import com.avic.rong.MainActivity;
import com.avic.rong.MyApplication;
import com.avic.rong.R;
import com.avic.rong.api.AlipayPayParamApi;
import com.avic.rong.api.WeixinPayParamApi;
import com.avic.rong.bean.AliParamBean;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.utils.ConstantsUtils;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ToPayActivity extends RxAppCompatActivity {


    public static String ARG_URL = "arg_url";
    private static final int ALI_PAY_FLAG = 100;
    public static final String ARG_SOURCE = "toPayactivity";

    @BindView(R.id.webview)
    BridgeWebView webView;

    private  AliParamBean aliParamBean;
    private IWXAPI iwxapi;
    private int orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_pay);
        ButterKnife.bind(this);

        String url = null;
        if (getIntent() != null){
            url = getIntent().getStringExtra(ARG_URL);
        }

        if (!TextUtils.isEmpty(url)) {
            webView.loadUrl(url);
        }

        iwxapi = WXAPIFactory.createWXAPI(this, ConstantsUtils.APP_ID);

        webView.registerHandler("pushVc", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                data = data.replace("\\", "");
                JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
                String urlString = jsonObject.get("url").getAsString();
                if(MyApplication.getInstance().userLoginBean != null){
                    if (urlString.contains("?")){
                        urlString = urlString + "&userIdSign=" + MyApplication.getInstance().userLoginBean.getUserId();
                    }else{
                        urlString = urlString + "?userIdSign=" + MyApplication.getInstance().userLoginBean.getUserId();
                    }
                }

                if (urlString.contains("pay/payFinish")) {//到店支付，余额支付
                    startActivity(PayFinishActivity.queryIntent(ToPayActivity.this,urlString));
                }else if (urlString.contains("/cservice")){//在线客服
                    Intent intent = new Intent();
                    intent.setData(Uri.parse(urlString));
                    intent.setAction(Intent.ACTION_VIEW);
                    startActivity(intent);
                }
            }
        });


        //微信支付
        webView.registerHandler("wxPay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                data = data.replace("\\", "");
                JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
                orderId = jsonObject.get("orderId").getAsInt();
                MyApplication.getInstance().orderId = orderId;
                WeixinPayParamApi weixinPayParamApi = new WeixinPayParamApi(ToPayActivity.this,weixinParamListener);
                weixinPayParamApi.setArgs(MyApplication.getInstance().userLoginBean.getUserId(),orderId);
                HttpManager.getInstance().doHttpDeal(weixinPayParamApi);
            }
        });

        //支付宝支付
        webView.registerHandler("aliPay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                data = data.replace("\\", "");
                JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
                orderId = jsonObject.get("orderId").getAsInt();

                AlipayPayParamApi alipayPayParamApi = new AlipayPayParamApi(ToPayActivity.this,aliParamListener);
                alipayPayParamApi.setArgs(MyApplication.getInstance().userLoginBean.getUserId(),orderId);
                HttpManager.getInstance().doHttpDeal(alipayPayParamApi);
            }
        });

        //去标准首页
        webView.registerHandler("pushOrderBZ", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                data = data.replace("\\", "");
                JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
                startActivity(OrderListActivity.queryIntent(ToPayActivity.this, jsonObject.get("url").getAsString() + "?userIdSign=" + MyApplication.getInstance().userLoginBean.getUserId(),ARG_SOURCE));
            }
        });


        //首页
        webView.registerHandler("homeClick", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                EventBus.getDefault().postSticky(new HomePageEvent());
                Intent intent = MainActivity.queryIntent(ToPayActivity.this);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        //搜索
        webView.registerHandler("searchClick", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = MainActivity.queryIntent(ToPayActivity.this);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                startActivity(SearchIndexActivity.queryIntent(ToPayActivity.this, AppUtils.BASE_URL + "app/searchIndex?type=0",UserMoneyListActivity.ARG_FROM_MONEY_LIST));
            }
        });
        //我的融融
        webView.registerHandler("memberClick", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                EventBus.getDefault().postSticky(new MinePageEvent());
                Intent intent = MainActivity.queryIntent(ToPayActivity.this);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });


        webView.registerHandler("goBack", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (webView.canGoBack()){
                    webView.goBack();
                }else{
                    finish();
                }
            }
        });
    }


    private HttpOnNextListener weixinParamListener = new HttpOnNextListener<BaseResultEntity>(){
        @Override
        public void onNext(BaseResultEntity entity) {
            if (entity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)){
//                {package=Sign=WXPay, appid=wx1a2342346402f5b2, sign=7EA6D28FE607ACF0826B58E8329F6E26, partnerid=1520266311, prepayid=wx25105753840424acde38efc40884413910, noncestr=l29HNsmfdzLsSwew, timestamp=1545706844}
                System.out.println("----------------------------uu--" + entity.toString());
                Map<String,Object> resultMap = (Map<String, Object>) entity.getData();
                PayReq req = new PayReq();
                //req.appId = "wxf8b4f85f3a794e77";  //appId
                req.appId			= (String) resultMap.get("appid");
                req.partnerId		= (String)resultMap.get("partnerid");
                req.prepayId		= (String) resultMap.get("prepayid");
                req.nonceStr		= (String) resultMap.get("noncestr");
                req.timeStamp		= (String) resultMap.get("timestamp");
                req.packageValue	= (String) resultMap.get("package");
                req.sign			= (String) resultMap.get("sign");
                req.extData			= "app data"; // optional
                iwxapi.sendReq(req);
            }else{
            }
        }
    };



    private HttpOnNextListener aliParamListener = new HttpOnNextListener<BaseResultEntity>(){

        @Override
        public void onNext(BaseResultEntity entity) {
            if (entity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)){
                aliParamBean = (AliParamBean)entity.getData();
                System.out.println("----------------------------uu--" + aliParamBean.toString());
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(ToPayActivity.this);
                        Map<String, String> result = alipay.payV2(aliParamBean.getOrderString(), true);
                        System.out.println("--------------------sp--" + result.toString() );
                        Message msg = new Message();
                        msg.what = ALI_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }else{

            }
        }
    };


    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ALI_PAY_FLAG: {//阿里支付成功之后,支付失败的结果页面
                    String resultStr = msg.obj.toString();
                    int startPos = resultStr.indexOf("code") - 2;
                    int endPos = resultStr.indexOf("sign") - 2;
                    resultStr = resultStr.substring(1,resultStr.length());

                    Pattern pattern = Pattern.compile("(code\":\"(\\d*))");
                    Matcher matcher = pattern.matcher(resultStr);
                    int payStatus = 1;//1:成功 ,2失败
                    String codeStr = "";
                    if (matcher.find()){
                        codeStr = matcher.group(2);
                    }
                    if (!codeStr.equals("10000")){//阿里支付成功的code
                        payStatus = 2;
                    }
                    startActivity(PayResultActivity.queryIntent(ToPayActivity.this, AppUtils.BASE_URL + "app/pay/payFinish2?orderId=" + orderId + "&payStatus=" + payStatus));
                }
            }
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().removeAllStickyEvents();
    }

    public static Intent queryIntent(Context context, String url){
        Intent intent = new Intent(context,ToPayActivity.class);
        intent.putExtra(ARG_URL,url);
        return intent;
    }
}
